#
# This file is an example of how to define handlers for callback
# and updates
#

#
# An example of an Handler of incoming response
# Using a callable class makes it easy to associate state to each handler
# All callables take two arguments:
#
# the first one is a dictionary containing all key:value in the GET url together
# with the dictionary optionally present as json encoded string in the body of the request
#
# the second parameter is the list of all url components following the url address of
# the request (the postpath)
#

import os
import time
from json import dumps
from mediadart.rest.twisted_server import Dispatcher


def get_filename(rootdir, request_id):
    return os.path.join(rootdir, 'out.%03d' % int(request_id))

def remove_files(rootdir):
    n = 0
    while 1:
        filename = get_filename(rootdir, n)
        if os.path.exists(filename):
            os.remove(filename)
        else:
            break
        n = n + 1

class ExampleCallback:
    """
    This class saves the replies in a file under rootdir, using the file name
    computed by get_filename.
    It could write in a database etc.
    """
    def __init__(self, rootdir='.'):
        self.rootdir = rootdir
        if not os.path.exists(self.rootdir):
            os.mkdir(self.rootdir)
        remove_files(self.rootdir)
        self.req_id = 0

    def log(self, data, postpath):
        fname = get_filename(self.rootdir, self.req_id)
        self.req_id += 1
        msg = 'msg_id = %s\n' % postpath
        msg += 'result = %s\n' % data
        f = open(fname, 'w')
        f.write(msg)
        f.close()
        print('Writing %s' % (fname))
        print('Received:\n%s' % msg)
        return 'ok'

class ExampleUpdater:
    """
    This class receives update messages and logs them on console.
    """
    def __call__(self, args, jobid, completion):
        msg = 'Update message: job %s completed at %s%%' % (jobid, completion)
        print "\n#####", msg
        return msg

class ExamplePing:
    def __call__(self, data, postpath=[]):
        return 'ExamplePing: %s' % str(data)


handlers_db = {
# ULR: handler
    'reply2': ExampleCallback('/tmp/results').log,
    'updates': ExampleUpdater(),
    'ping': ExamplePing(),
}

def start_server(root):
    for url, handler in handlers_db.items():
        root.putChild(url, Dispatcher(handler))

